/**
 * MiniGolf Scorecard
 * Copyright (C) 2010  MiriTheQuiet, http://minigolfscorecard.googlecode.com/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package cz.mtq.mgsc.model;

import java.util.Vector;

public final class Players {

	private Vector players = null;

	public void initPlayers(byte numberOfUsers) {
		if (players == null) {
			players = new Vector(numberOfUsers);
		} else {
			players.removeAllElements();
			players.ensureCapacity(numberOfUsers);
		}
	}

	public void addPlayer(Player u) {
		players.addElement(u);
	}

	public int size() {
		return players != null ? players.size() : 0;
	}

	public Vector getPlayers() {
		return players;
	}

	public Player getPlayer(int index) {
		return (Player) players.elementAt(index);
	}

	/**
	 * Player with lowest {@link Player#getSum()} is first.
	 * TODO use faster sorting algorithmus
	 */
	public void sortPlayers() {
		// bubble sort
		while (true) {
			boolean sortOccured = false;
			for (int i = 0; i < players.size(); i++) {
				Player u1 = (Player) players.elementAt(i);
				if (i + 1 <= players.size() - 1) {
					Player u2 = (Player) players.elementAt(i + 1);
					if (u1.getSum() > u2.getSum()) {
						players.insertElementAt(u2, i);
						players.removeElementAt(i + 2);
						sortOccured = true;
					}
				}
			}
			if (!sortOccured) {
				break;
			}
		}
	}

}
